import {
	getToken,
	setToken,
} from "@/utils/storage/modules/auth"
import {
	getUserInfo,
	setUserInfo,
} from "@/utils/storage/modules/user"
import http from '@/api/index'



const state = {
	token: getToken(),
	userInfo: getUserInfo(),
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
		setToken(token)
	},
	SET_USER_INFO: (state, userInfo) => {
		state.userInfo = userInfo
		setUserInfo(userInfo)
	},

}

const actions = {
	setToken({
		commit
	}, data) {
		console.log(data)
		return new Promise(resolve => {
			commit("SET_TOKEN", data)
			resolve(data)
		})
	},
	setUserInfo({
		commit
	}, data) {
		return new Promise(resolve => {
			commit("SET_USER_INFO", data)
			resolve(data)
		})
	},
	// 登录
	loginCheck({
		commit,
		dispatch
	}, form) {
		return new Promise((reslove, reject) => {
			let api = ''
			// if (form.password2) {
			// 	api = http.register(form)
			// } else {
			api = http.login(form)
			// }
			api.then(async res => {
					console.log(res, '登录')
					if (res.data && res.data.accessToken) {
						commit("SET_TOKEN", res.data.accessToken)
						await dispatch('getUser', form)
					}
					reslove(res)
				})
				.catch(err => {
					reject(err)
				})
		})
	},
	getUser({
		commit,
		state,
		dispatch
	}, params) {
		return new Promise(async (resolve, reject) => {
			let {
				data
			} = await http.getUserInfo()
			commit("SET_USER_INFO", data || {})
			resolve(data)
		})
	},


	logout({
		commit,
		state,
		dispatch
	}, params) {
		return new Promise((resolve, reject) => {
			//清理缓存
			uni.clearStorageSync();
			// #ifdef APP-PLUS
			//清除应用中的缓存数据
			plus.cache.clear();
			// #endif
			uni.reLaunch({
				url: "/pages/Login/Login"
			})
			resolve()
		})
	},
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}